export default {
	data() {
		return {
			woProducts: [],
			woTransInfo: {},
			woCacheData: {},
		}
	},
	methods: {
		async GetOrderData() {
			let uPhone = this.UserInfo.mobile;
			let token = this.UserInfo.RetId
			let result = await this.workorderlistervice.CacheOrderInfoAsync(uPhone, 2, this.orderDetailId, "",
				token);
		
			if (result && result.RetBool) {
				let data = JSON.parse(result.RetObject);
				this.orderDetailData = JSON.parse(data.NewWoData);
				//let CacheData = data.CacheWoData?JSON.parse(data.CacheWoData):null;
				console.log("orderDetailData", this.orderDetailData);
			} else {
				uni.showToast({
					title: "获取工单信息失败" + result.RetMsg,
					icon: "none"
				});
			}
			uni.hideLoading();
		},
		
		// 获取区域列表
		async GetAddressList(IdentifyName, FilterId) {
			let uPhone = this.UserInfo.mobile;
			let token = this.UserInfo.RetId;
			let result = await this.workordercompleteservice.AddressListAsync(uPhone, IdentifyName, FilterId, token);
			if (result && result.RetBool) {
				let data = JSON.parse(result.RetObject);
				this.areaList = data;
				//let CacheData = data.CacheWoData?JSON.parse(data.CacheWoData):null;
				console.log("areaList", this.areaList);
			} else {
				uni.showToast({
					title: "获取工单信息失败" + result.RetMsg,
					icon: "none"
				});
			}
		},
		
		//解析数据
		initData(WoData) {
			debugger;
			//赋值工单头数据
			this.AssignOrderInfo(WoData);
			var tempWoFinishedProList = [];
			//debugger;
			if (WoData.ShelfLife == 1)
				this.isShowActualReceiptAmountField = true;
			for (let index in WoData.WoProuduct) {
				//物流码
				let itemPro = WoData.WoProuduct[index]
				let result = this.IsLogisticsCodeAndProductFill(itemPro, WoData);
				let fp_ProInfoItem = {
					'WoObjectId': itemPro.WoObjectId,
					'proHisNum': itemPro.ProductNum,
					'proHisId': itemPro.ProuctId,
					'proHisTypeGroup': itemPro.ProdTypeGroup,
					'proHisName': itemPro.ProductName,
					'proHisPurchaseSourceName': itemPro.PurchaseSourceText,
					'proHisPurchaseStoreName': itemPro.PurchaseChanel,
					'proHisBarcode': itemPro.Barcode,
					'proHisIsValidBarcode': itemPro.IsSerialValid,
					'proHisPurchaseDate': itemPro.PurchaseDate,
					'ProductNum': itemPro.ProductNum,
					'ProuctId': itemPro.ProuctId,
					'ProdTypeGroup': itemPro.ProdTypeGroup,
					'ProductName': itemPro.ProductName,
					'PurchaseSourceText': itemPro.PurchaseSourceText,
					'InstallLocation': itemPro.InstallLocation,
					'PurchaseChanel': itemPro.PurchaseChanel,
					'PurchaseDate': itemPro.PurchaseDate,
					'Barcode': itemPro.Barcode,
					'IsSerialValid': itemPro.IsSerialValid,
					'ProductImage': (itemPro.ProductImage != null && itemPro.ProductImage != 'null' && itemPro.ProductImage != '') ?
						"data:image/jpeg;base64," + itemPro.ProductImage : "",
					'IsProductConfirmed': itemPro.IsProductConfirmed,
					'proOriBarcode': itemPro.Barcode,
					'isBarcodeRequired': result.isBarcodeRequired,
					'isCheckBarcode': result.isCheckBarcode,
					'isShowBarcodeCheckBtn': false,
					'isDisplayProdInputField': result.isDisplayProdInputField,
					'isDisplayNewProdInputField': true,
					'isShowNewBarcodeCheckBtn': false,
					'proNewInstallPosition': null,
					'proIsNewBarcodeRequired': result.isBarcodeRequired,
					'proIsCheckNewBarcode': false,
					'proNewBarcode': null,
					'proNewProductID': null,
					'proNewProductName': null,
					'proNewProductNum': null,
					'proOriNewBarcode': null,
					'proCustProdID': itemPro.CustProductId,
					'WaterAnalysisFieldRequired': itemPro.WaterAnalysisFieldRequired,
					'OriWaterAnalysisId': itemPro.OriWaterAnalysisId,
					'ProductSeriesId': itemPro.ProductSeriesId,
					'ProductSeriesName': itemPro.ProductSeriesName,
					'OriTDS': itemPro.OriTDS,
					'OriTemperature': itemPro.OriTemperature,
					'OriHardness': itemPro.OriHardness,
					'OriChlorine': itemPro.OriChlorine,
					'NewTDS': itemPro.NewTDS,
					'NewHardness': itemPro.NewHardness,
					'NewChlorine': itemPro.NewChlorine,
					'IsRequired': itemPro.IsRequired,
					'IsWaterAnalysis': false,
					'isShowWaterAnalysisAddBtn': (itemPro.OriWaterAnalysisId != null && itemPro.OriWaterAnalysisId != 'null' &&
						itemPro.OriWaterAnalysisId != '') ? false : true,
					'WarrantyEndDate': itemPro.WarrantyEndDate,
					'WarrantyStartDate': itemPro.WarrantyStartDate,
					'SuitProductName': itemPro.SuitProductName,
					'SuitProductDescription': itemPro.SuitProductDescription,
					'OnlyChangeEndDate': itemPro.OnlyChangeEndDate,
					'maintenanceIndex': itemPro.maintenanceIndex ? itemPro.maintenanceIndex : 0,
					'ProductMaintainData': itemPro.Maintains ? itemPro.Maintains : null,
				};
				console.log(this.NewProductList);
				tempWoFinishedProList.push(fp_ProInfoItem)
			}
			WoData.WoProuduct = tempWoFinishedProList;
		
		},
		
		async GetOrderDataImg() {
			let UsePhone = this.UserInfo.mobile;
			let token = this.UserInfo.RetId
		
			let result = await this.workorderlistervice.CacheOrderInfoAsync(UsePhone, 2,
				this.orderDetailId, "",
				token);
			if (result && result.RetBool) {
				let data = JSON.parse(result.RetObject);
				let orderDetailData = JSON.parse(data.NewWoData);
				return orderDetailData.WoItemPicture;
			}
		
		},
		
		//确认产品
		async AffirmProduct(index) {
			let prodect = this.orderDetailData.WoProuduct[index];
			console.log(prodect);
			if (!prodect.Barcode) {
				uni.showToast({
					title: "物流码不能为空",
					icon: "none"
				});
				return;
			}
			if (!prodect.PurchaseDate) {
				uni.showToast({
					title: "保修开始时间不能为空",
					icon: "none"
				});
				return;
			}
			let result = await this.workordercompleteservice.ConfirmProductAsync(this.UserInfo.mobile, this.orderDetailData.WoFinishType,
				prodect.Barcode, prodect.ProuctId, prodect.WoObjectId, this.orderDetailId, prodect.PurchaseDate, this.UserInfo.RetId
			);
			console.log(result);
			if (result) {
				if (result.RetBool) {
					uni.showToast({
						title: "产品确认成功",
						icon: "none"
					});
					prodect.IsProductConfirmed = true;
					console.log(this.orderDetailData);
		
				} else {
					uni.showToast({
						title: `产品确认失败:${result.RetMsg}`,
						icon: "none"
					});
				}
			} else {
				uni.showToast({
					title: "产品确认失败!",
					icon: "none"
				});
			}
			uni.hideLoading();
		},
		
		//验证物理码
		async BarcodeValidCheckAsync(index, Barcode) {
			let userPhone = this.UserInfo.mobile
			let token = this.UserInfo.RetId
			let result = await this.workordercompleteservice
				.BarcodeValidCheckAsync(userPhone, Barcode, token);
			if (result && result.RetBool) {
				let data = JSON.parse(result.RetObject);
				return data;
			} else {
				console.log(result.RetMsg);
				throw result.RetMsg;
			}
		},
		
		//验证后刷新产品信息
		RefreshProduct(data, index, Barcode) {
			//debugger;
			let productItem = this.orderDetailData.WoProuduct[index];
			if (data && data.IsValid) {
				//debugger
				productItem.Barcode = Barcode;
				productItem.IsSerialValid = "有效";
				if (data.ItemIdGUID) {
					productItem.ProductNum = data.ProductName;
					productItem.ProductName = data.ProductNum;
					productItem.ProuctId = data.ItemIdGUID;
					productItem.ProdTypeGroup = data.ProductTypeGroupName;
					productItem.WaterAnalysisFieldRequired = data.WaterAnalysisFieldRequired;
					productItem.ProductImage = (data.ProductImage != null && data.ProductImage != 'null' && data.ProductImage != '') ?
						"data:image/jpeg;base64," + data.ProductImage : "";
					productItem.proFaultyGroup = data.FaultyGroup;
					productItem.proFaultyGroupName = data.FaultyGroupName;
					productItem.IsRequired = data.IsRequired;
					productItem.isCheckBarcode = true;
					productItem.isDisplayProdInputField = true;
					uni.hideLoading();
				} else {
					productItem.isCheckBarcode = true;
					productItem.isDisplayProdInputField = false;
					uni.hideLoading();
					uni.showToast({
						title: "物流码有效，但没有匹配到关联产品，请从产品选择",
						icon: "none",
						duration: 3000
					});
				}
			} else {
				productItem.Barcode = "";
				uni.hideLoading();
				uni.showToast({
					title: "物流码无效，请重新输入",
					icon: "none",
					duration: 3000
				});
			}
		},
		
		IsLogisticsCodeAndProductFill(itemPro, woData) {
			//物流码是否可填
			let isBarcodeRequired = false;
			//产品是否可填
			let isDisplayProdInputField = true;
			//
			let isCheckBarcode = false;
			if (itemPro.IsProductConfirmed == false) {
				// ShelfLife【1：保外；2：保内；3：保外转保内】
				// InWarrantySerialCtrl；OutWarrantySerialCtrl【1：不验证；2：工单完工验证；3：产品确认验证】
				console.log("保内保外：", woData.ShelfLife);
				console.log("保内控制：", woData.InWarrantySerialCtrl);
				console.log("保外控制：", woData.OutWarrantySerialCtrl);
				if (woData.ShelfLife == 1 && woData.InWarrantySerialCtrl != 1) {
					isBarcodeRequired = true;
				} else if (woData.ShelfLife == 2 && woData.OutWarrantySerialCtrl != 1) {
					isBarcodeRequired = true;
				} else {
					isDisplayProdInputField = false;
				}
			} else {
				isCheckBarcode = true;
			}
			return {
				isBarcodeRequired: isBarcodeRequired,
				isDisplayProdInputField: isDisplayProdInputField,
				isCheckBarcode: isCheckBarcode
			};
		},
		
		//给工单信息赋值
		AssignOrderInfo(woData) {
			this.OrderRremark = woData.WORemark; //备注
			this.CustomerRequiresMaintenanceDate = woData.CustomerRequiresMaintenanceDate ?
				woData.CustomerRequiresMaintenanceDate : ""; //客户产品日期
			this.ActualReceiptAmount = woData.ActualReceivedAmount ? woData.ActualReceivedAmount : ""; //实际金额
			// this.repairTypeIndex = woData.RepairType ? woData.RepairType - 1 : 0; //维修方式
			this.addressDetail=woData.Street;
			//console.log("日期信息",this.CustomerRequiresMaintenanceDate,woData.CustomerRequiresMaintenanceDate);
		},
		
		//提交工单
		async SubmitOrder() {
			uni.showLoading({
				title: "提交中..",
				mask: true,
			})
			//数据检测
			let IsAllValid = this.CheckDataBySubmitFinish();
			if (IsAllValid) {
				this.ConstructWoSubmitDataObject(); //构建完工对象
				let strCacheData = this.GetCacheOrderInfo(); //构建缓存对象
				console.log(this.woProducts, this.woTransInfo)
				debugger
				let result = await this.workordercompleteservice.WOSubmitActionAsync(this.UserInfo.mobile, this.woTransInfo, this.woProducts,
					strCacheData, this.UserInfo.RetId)
				uni.hideLoading();
				if (result) {
					if (result.RetBool) {
						uni.showToast({
							title: "提交完工成功",
							icon: "none",
							duration: 3000
						});
						uni.switchTab({
							url: '../../workorder/index',
							success: () => {
								uni.$emit("ReLoadWorder");
							}
						});
					} else {
						uni.showToast({
							title: "提交完工失败:" + result.RetMsg,
							icon: "none",
							duration: 3000
						});
					}
				} else {
					uni.showToast({
						title: "提交完工失败",
						icon: "none",
						duration: 3000
					});
				}
			}
			
		},
		//构建缓存信息
		GetCacheOrderInfo() {
			//工单信息
			this.woCacheData.FinishType = this.orderDetailData.WoFinishType;//完工类型
			this.woCacheData.Description = this.OrderRremark //备注
			this.woCacheData.RepairType = "";//维修方式
			this.woCacheData.IsRepalced = false;//是否换件
			this.woCacheData.ActualReceivedAmount = this.ActualReceiptAmount;//实际收款总金额
			this.woCacheData.CustomerRequiresMaintenanceDate = this.CustomerRequiresMaintenanceDate;//客户服务时间
			
			this.woCacheData.Province=this.orderDetailData.ProvinceId; // 新省/市
			this.woCacheData.City= this.orderDetailData.CityId; // 新市/区
			this.woCacheData.County= this.areaList[this.areaIndex].AddressId; // 新区/县
			this.woCacheData.Street=this.addressDetail; // 新街道
			
			this.woCacheData.WoProduct = [];//产品信息
			for (let index in this.orderDetailData.WoProuduct) {
				let prodItem = this.orderDetailData.WoProuduct[index];
				let prodImg;//图片
				if (prodItem.ProductImage) {
					prodImg = prodItem.ProductImage.replace("data:image/jpeg;base64,", "");
				}
				let product = {
					ServiceOrderObject: prodItem.WoObjectId, // 服务工单对象
					Barcode: prodItem.Barcode, // 物流码
					New_Barcode: "", //换机新物流码
					IsSerialValid: prodItem.IsSerialValid,//物流码有效性
					PurchaseDate: prodItem.PurchaseDate, // 购机日期
					Product: prodItem.ProuctId, // 产品
					ProdTypeGroup: prodItem.ProdTypeGroup,//产品类型
					ProductImage: prodImg,//图片
					ProductName: prodItem.ProductName,//产品名称
					ProductNum: prodItem.ProductNum,//产品编号
					Province: "", // 新省/市
					City: "", // 新市/区
					County: "", // 新区/县
					Street: "", // 新街道
					InstalledLocation: prodItem.InstallLocation, // 安装位置
					InstalledLocatuion_New: prodItem.InstallLocation, // 新安装位置
					SuitProductItems: "",//套装产品项
					Repairs: [],//维修信息
					Maintains: [],//保养信息
					WaterAnalysis: {} //水质检测
				};
				this.woCacheData.WoProduct.push(product);
			}
			console.log("this.woCacheData",this.woCacheData);
			return JSON.stringify(this.woCacheData);
		},
		
		//构造工单完工提交数据对象
		ConstructWoSubmitDataObject() {
			this.woTransInfo = {};
			this.woProducts = [];
			this.woTransInfo.ServiceOrder = this.orderDetailId;
			this.woTransInfo.Operator = ""; // 操作服务工程师
			this.woTransInfo.Type = 20; // 工单事务类型
			this.woTransInfo.FinishType = this.orderDetailData.WoFinishType; // 完工类型
			this.woTransInfo.Description = this.OrderRremark //备注
			this.woTransInfo.RepairType = "";
			this.woTransInfo.IsRepalced = false;
			this.woTransInfo.ActualReceivedAmount = this.ActualReceiptAmount;
			
			this.woTransInfo.Province=this.orderDetailData.ProvinceId; // 新省/市
			this.woTransInfo.City= this.orderDetailData.CityId; // 新市/区
			this.woTransInfo.County= this.areaList[this.areaIndex].AddressId; // 新区/县
			this.woTransInfo.Street=this.addressDetail; // 新街道
			
			this.woTransInfo.CustomerRequiresMaintenanceDate = this.CustomerRequiresMaintenanceDate;
			debugger
			for (let index in this.orderDetailData.WoProuduct) {
				let prodItem = this.orderDetailData.WoProuduct[index];
				let product = {
					ServiceOrderObject: prodItem.WoObjectId, // 服务工单对象
					Barcode: prodItem.Barcode, // 物流码
					New_Barcode: "", //换机新物流码
					PurchaseDate: prodItem.PurchaseDate, // 购机日期
					Product: prodItem.ProuctId, // 产品
					InstalledLocation: prodItem.InstallLocation, // 安装位置
					InstalledLocatuion_New: prodItem.InstallLocation, // 新安装位置
					SuitProductItems: "",
					Repairs: [],
					Maintains: [],
					WaterAnalysis: {}
				};
				this.woProducts.push(product);
			}
			console.log("this.woTransInfo",this.woTransInfo);
			console.log("this.woProducts",this.woProducts);
			debugger
		},
		
		//完工数据检测
		CheckDataBySubmitFinish() {
			let toastduration = 3000
			//完工备注
			if (this.OrderRremark != "") {
				let IsContainSpecial = this.CheckSpecial(this.OrderRremark);
				if (IsContainSpecial) {
					uni.showToast({
						title: "完工备注不能包含如下特殊字符(%()\;:\'\",.\\/)",
						icon: "none",
						duration:toastduration
					});
					return false;
				}
			}
			//验证产品选择、物流码输入字段、购机日期、装机位置
			for (let index in this.orderDetailData.WoProuduct) {
				let ProductItem = this.orderDetailData.WoProuduct[index];
				let proIsConfirmed = ProductItem.IsProductConfirmed
				let proBarcode = ProductItem.Barcode;
				let proNum = ProductItem.ProductNum;
				let isBarcodeRequired = ProductItem.IsBarcodeRequired;
				let proInstallPosition = ProductItem.InstallLocation;
				let proPurchaseDate = ProductItem.PurchaseDate;
				if (!proIsConfirmed) {
					let proId = ProductItem.ProuctId;
					if (proId == null || proId == "") {
						uni.showToast({
							title: "产品字段不能为空值，请选择！",
							icon: "none",
							duration:10000
						});
						return false;
					}
					if (proBarcode && proBarcode != "") {
						let isCheckBarcode = ProductItem.isCheckBarcode;
						if (isCheckBarcode != true) {
							uni.showToast({
								title: `产品：${proNum}输入的物流码未验证！`,
								icon: "none",
								duration:10000
							});
							return false;
						}
					} else if (isBarcodeRequired == true && (proBarcode == null || proBarcode == "")) {
						uni.showToast({
							title: `产品：${proNum}物流码不能为空！`,
							icon: "none",
							duration:10000
						});
						return false;
					}
				}
				if (proInstallPosition == null || proInstallPosition == "") {
					uni.showToast({
						title: `产品：${proNum}装机位置不能为空！`,
						icon: "none",
						duration:10000
					});
					return false;
				} else {
					let isContainSpecial = this.CheckSpecial(proInstallPosition);
					if (isContainSpecial == true) {
						uni.showToast({
							title: '安装位置不能包含如下特殊字符--%()\;:\'\",.\\/',
							icon: "none",
							duration:10000
						});
						return false;
					}
				}
				if (proBarcode != null && proBarcode != "") {
					let isContainSpecial = this.CheckSpecial(proBarcode);
					if (isContainSpecial == true) {
						uni.showToast({
							title: '物流码不能包含如下特殊字符',
							icon: "none",
							duration:10000
						});
						return false;
					}
				}
			}
			// 验证实际收款总金额字段
			if (this.isShowActualReceiptAmountField == true) {
				let valAmount = this.ActualReceiptAmount;
				if (valAmount === null || valAmount === "" || valAmount === undefined) {
					uni.showToast({
						title: "实际收款总金额不能为空！",
						icon: "none"
					});
					return false;
				}
			}
			return true;
		},
		
		CheckSpecial: function(str) {
			var containSpecial = RegExp(/[(\%)(\()(\))(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)]+/);
			return (containSpecial.test(str));
		},
	}
}
